package top.zhangjianyong.tools.bill.manager;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import top.zhangjianyong.tools.entity.BillFile;
import top.zhangjianyong.tools.entity.WaBill;
import top.zhangjianyong.tools.bill.manager.resolver.AliBillFileResolver;
import top.zhangjianyong.tools.bill.manager.resolver.BillFileResolver;
import top.zhangjianyong.tools.utils.FileUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class BillFileResolverManager {
    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 账单数据解析入库
     *
     * @param lines
     */
    public void resolve(List<String> lines, BillFile billFile) {
        BillFileResolver resolver = getResolver(lines);
        List<WaBill> list = resolver.resolve(lines, billFile);

        //获取账单开始结束日期
        LocalDate start = list.stream().map(bill -> bill.getTradeTime().toLocalDate())
                .min(LocalDate::compareTo).orElse(null);
        LocalDate end = list.stream().map(bill -> bill.getTradeTime().toLocalDate())
                .max(LocalDate::compareTo).orElse(null);
        billFile.setStartDate(start);
        billFile.setEndDate(end);
        billFile.setPlatform(resolver.getPlatform());
        billFile.setTotal(list.size());
        billFile.setState("解析完成");
    }


    /**
     * 获取账单文件解析器
     *
     * @param lines
     * @return
     * @throws Exception
     */
    public BillFileResolver getResolver(List<String> lines) {
        return getBillFileResolverMap()
                .values()
                .stream()
                .filter(billFileResolver -> billFileResolver.canResolver(lines))
                .findAny()
                .orElseThrow(() -> new RuntimeException("未找到对应的对账文件解析器"));
    }

    /**
     * 获取全部解析器
     */
    public Map<String, BillFileResolver> getBillFileResolverMap() {
        return applicationContext.getBeansOfType(BillFileResolver.class);
    }

    public void reload() {
        getBillFileResolverMap().values().forEach(BillFileResolver::reload);
    }

    public static void main(String[] args) throws IOException {
        File file = new File("/Users/zhangjianyong/IdeaProjects/zhangjianyongTools/alipay_record_20230315_214614.csv");
        String fileCharset = FileUtil.getFileCharset(file);
        log.info("文件编码>>>{}", fileCharset);
        //解析文件
        List<String> billLines = IOUtils.readLines(new FileInputStream(file), Charset.forName(fileCharset));
        AliBillFileResolver aliBillFileResolver = new AliBillFileResolver(null);
        aliBillFileResolver.canResolver(billLines);
    }
}
